package util

import (
	"fmt"
	"gitee.com/kristas/booting-go/framework/common/util/lang"
	"log"
	"os"
	"strings"
)

const (
	importFlag = "import ("
	apiFuncTpl = "\n%sfunc (%s *%s) %s(%s) %s {\n  panic(\"implement your logic\") \n}\n"
)

func WriteImports(fileName string, imports []string) error {
	tmp := lang.NewString(importFlag)
	for _, s := range imports {
		if s == "" {
			continue
		}
		tmp = tmp.Concat("\n", "\t", fmt.Sprintf(`"%s"`, s))
	}
	err := ReplaceFileContents(importFlag, tmp.String(), 1, func(mode int) (*os.File, error) {
		return OpenFile(fileName, mode)
	})
	if err != nil {
		return err
	}
	return nil
}

func WriteFunction(fileName, receiver string, isPtr bool, structName, methodName, param, response string, annotation ...string) error {
	file, err := OpenFile(fileName, os.O_APPEND|os.O_RDWR)
	if err != nil {
		return err
	}
	defer file.Close()
	var annotationStr string
	if len(annotation) != 0 {
		annotation[0] = fmt.Sprintf("// %s %s", methodName, annotation[0])
		annotationStr = strings.Join(annotation, "\n//")
		annotationStr += "\n"
	}
	function := fmt.Sprintf(apiFuncTpl, annotationStr, receiver, structName, methodName, param, response)
	_, err = file.WriteString(function)
	if err != nil {
		return err
	}
	return nil
}

func BuildImport(pkg string) string {
	currPkg, err := GetPkgName()
	if err != nil {
		log.Fatal(err)
	}
	return currPkg + "/" + pkg
}
